import sqlite3
import re

#this module mainly the work of spiderman, of http://drupal.tranzform.ca fame

def main(self, sender, channel, flags, message, DB, DEBUG):

    #connect to the db, check to see if an item exists, and what it's karma is
    def karma(item,val=0):
        print '|%s|'%(item,)
        karma_con=sqlite3.connect(DB)
        try:
            cur = karma_con.execute("select score from karma where item = ?", (item,))
            score = cur.next()[0]
            cur.close()
        except:
            score = None

        if val == 0:
            karma_con.close()
            return score
        else:

            sth = karma_con.cursor()

	    #if an item doesn't have any entry, add one to the database
            if score is None:
                sth.execute("insert into karma (item,score) values (?, ?)", (item,val))
                sth.close()
                karma_con.commit()

	    #if an item has an entry, update it's score
            else:
                sth.execute("update karma set score = ? where item = ?", (score+val,item))
                sth.close()
                karma_con.commit()
                karma_con.close()
                return score+val
        karma_con.close()

    #check message for karma ++ rating
    karma_re = re.compile( r'(\S+)\s?\+\+', re.I)
    for item in re.findall(karma_re, message):
        karma(item,1)
         if DEBUG == True:
            print "found karma item: %s" %(item)

    #check message for karma -- rating
    karma_re = re.compile( r'(\S+)\s?--', re.I)
    for item in re.findall(karma_re, message):
        karma(item,-1)
         if DEBUG == True:
            print "found neg karma item: %s" %(item)

    #check message, looking for "karma for foo?" type string and query database
    re_karma = re.compile( r'karma for (\S+)', re.I)
    for item in re.findall(re_karma, message):
        if item.endswith('?'):
            item = item.replace('?','')
            k = karma(item)
             if DEBUG == True:
                print "found request for karma: %s" %(item)
            self.send_channel_message(channel, '%s has %s karma' %(item,k))
